# Makefile for RK Vendor Storage Writer
# Author: Zhang Zhen <zhangzhen@cmhi.chinamobile.com>

# Directories
SRC_DIR = src
BIN_DIR = bin
SCRIPTS_DIR = scripts
SERVICE_DIR = service
CONFIG_DIR = config

# User space programs
USER_PROGRAMS = rk_vendor_tui
CC = gcc
CFLAGS = -Wall -Wextra -O2

# Default Targets
TARGETS = $(BIN_DIR)/WriteSN $(BIN_DIR)/YamlSN

# Default target
all: $(BIN_DIR) $(TARGETS)

# Create bin directory
$(BIN_DIR):
	@mkdir -p $(BIN_DIR)

# Build WriteSN tool (interactive TUI for writing SN)
$(BIN_DIR)/WriteSN: $(SRC_DIR)/rk_vendor_tui.c
	@echo "Building WriteSN tool..."
	$(CC) $(CFLAGS) -o $@ $<

# Build YamlSN tool (boot service for reading SN to YAML)
$(BIN_DIR)/YamlSN: $(SRC_DIR)/rk_vendor_reader.c
	@echo "Building YamlSN tool..."
	$(CC) $(CFLAGS) -o $@ $<

# Install binaries to system directories
install: $(TARGETS)
	@echo "Installing RK vendor storage tools..."
	install -d /usr/bin
	install -m 755 $(BIN_DIR)/WriteSN /usr/bin/
	install -d /usr/local/bin
	install -m 755 $(BIN_DIR)/YamlSN /usr/local/bin/
	@echo "✓ WriteSN installed to /usr/bin/"
	@echo "✓ YamlSN installed to /usr/local/bin/"
	@echo "You can now run 'WriteSN' from anywhere!"

# Uninstall binaries from system directories
uninstall:
	@echo "Uninstalling RK vendor storage tools..."
	rm -f /usr/bin/WriteSN
	rm -f /usr/local/bin/YamlSN
	@echo "✓ Tools uninstalled"

# Clean build artifacts
clean:
	@echo "Cleaning build artifacts..."
	rm -rf $(BIN_DIR)
	rm -f *.o

# Test direct vendor storage access
test: user_programs
	@echo "Testing RK vendor storage direct access..."
	@echo "Checking if /dev/vendor_storage exists..."
	@if [ -c /dev/vendor_storage ]; then \
		echo "Device /dev/vendor_storage exists"; \
		ls -l /dev/vendor_storage; \
		echo "Writing configuration to vendor storage..."; \
		sudo ./rk_vendor_direct -w; \
		echo "Reading configuration from vendor storage..."; \
		sudo ./rk_vendor_direct -r; \
	else \
		echo "Device /dev/vendor_storage does not exist"; \
		echo "Make sure you are running on RK platform with vendor storage support"; \
	fi

# Show device status
status:
	@echo "Checking vendor storage device status..."
	@if [ -c /dev/vendor_storage ]; then \
		echo "Device /dev/vendor_storage exists"; \
		ls -l /dev/vendor_storage; \
	else \
		echo "Device /dev/vendor_storage does not exist"; \
		echo "Make sure you are running on RK platform"; \
	fi

# Help target
help:
	@echo "Available targets:"
	@echo "  all              - Build user space programs"
	@echo "  user_programs    - Build user space programs"
	@echo "  clean            - Clean all build artifacts"
	@echo "  test             - Test direct vendor storage access"
	@echo "  status           - Check vendor storage device status"
	@echo "  help             - Show this help message"

.PHONY: all user_programs clean test status help
